/**
 * 翻译
 * @param text
 * @param country
 * @returns {string}
 */
// function translate(text, country) {

//     let request = "";

//     const https = require("https")
//     const crypto = require("crypto")

//     // 计算HMAC-SHA256
//     function sha256(message, secret = "", encoding) {
//         const hmac = crypto.createHmac("sha256", secret)
//         return hmac.update(message).digest(encoding)
//     }

//     // 计算SHA256
//     function getHash(message, encoding = "hex") {
//         const hash = crypto.createHash("sha256")
//         return hash.update(message).digest(encoding)
//     }

//     function getDate(timestamp) {
//         const date = new Date(timestamp * 1000)
//         const year = date.getUTCFullYear()
//         const month = ("0" + (date.getUTCMonth() + 1)).slice(-2)
//         const day = ("0" + date.getUTCDate()).slice(-2)
//         return `${year}-${month}-${day}`
//     }

//     // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
//     // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性
//     // 以下代码示例仅供参考，建议采用更安全的方式来使用密钥
//     // 请参见：https://cloud.tencent.com/document/product/1278/85305
//     // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
//     const SECRET_ID = "AKIDtjbVDpMkxzujT4b5MjNuXIAstmojbXp0"
//     const SECRET_KEY = "3AXxT7i8NQpPyU4eEwss2U9mGeCkDlNq"
//     const TOKEN = ""

//     const host = "tmt.tencentcloudapi.com"
//     const service = "tmt"
//     const region = "ap-beijing"
//     const action = "TextTranslate"
//     const version = "2018-03-21"
//     const timestamp = parseInt(String(new Date().getTime() / 1000))
//     const date = getDate(timestamp)
//     // const payload = "{\"SourceText\":\"Nail Art Digital Printer\",\"Source\":\"auto\",\"Target\":\"zh\",\"ProjectId\":0}"
//     // console.log(payload)
//     const payload = "{\"SourceText\":\"" + text + "\",\"Source\":\"auto\",\"Target\":\"" + country + "\",\"ProjectId\":0}"
//     console.log(payload)

//     // ************* 步骤 1：拼接规范请求串 *************
//     const signedHeaders = "content-type;host"
//     const hashedRequestPayload = getHash(payload)
//     const httpRequestMethod = "POST"
//     const canonicalUri = "/"
//     const canonicalQueryString = ""
//     const canonicalHeaders = "content-type:application/json; charset=utf-8\n" + "host:" + host + "\n"

//     const canonicalRequest = httpRequestMethod + "\n" + canonicalUri + "\n" + canonicalQueryString + "\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + hashedRequestPayload

//     // ************* 步骤 2：拼接待签名字符串 *************
//     const algorithm = "TC3-HMAC-SHA256"
//     const hashedCanonicalRequest = getHash(canonicalRequest)
//     const credentialScope = date + "/" + service + "/" + "tc3_request"
//     const stringToSign = algorithm + "\n" + timestamp + "\n" + credentialScope + "\n" + hashedCanonicalRequest

//     // ************* 步骤 3：计算签名 *************
//     const kDate = sha256(date, "TC3" + SECRET_KEY)
//     const kService = sha256(service, kDate)
//     const kSigning = sha256("tc3_request", kService)
//     const signature = sha256(stringToSign, kSigning, "hex")

//     // ************* 步骤 4：拼接 Authorization *************
//     const authorization = algorithm + " " + "Credential=" + SECRET_ID + "/" + credentialScope + ", " + "SignedHeaders=" + signedHeaders + ", " + "Signature=" + signature

//     // ************* 步骤 5：构造并发起请求 *************
//     const headers = {
//         Authorization: authorization,
//         "Content-Type": "application/json; charset=utf-8",
//         Host: host,
//         "X-TC-Action": action,
//         "X-TC-Timestamp": timestamp,
//         "X-TC-Version": version,
//     }

//     if (region) {
//         headers["X-TC-Region"] = region
//     }
//     if (TOKEN) {
//         headers["X-TC-Token"] = TOKEN
//     }

//     const options = {
//         hostname: host, method: httpRequestMethod, headers,
//     }

//     const req = https.request(options, (res) => {
//         let data = ""
//         res.on("data", (chunk) => {
//             data += chunk
//         })
//         res.on("end", () => {
//             console.log(data)
//             request = data
//         })
//     })

//     req.on("error", (error) => {
//         console.error(error)

//     })

//     req.write(payload)

//     req.end()
//     return request

// }

/**
 * URL特殊字符转义方法
 * @param {string} url - 需要转义的URL字符串
 * @returns {string} 转义后的URL字符串
 */
function encodeURL(url) {
    // 定义需要转义的特殊字符及其编码
    const charMap = {
        ' ': '%20', '!': '%21', '"': '%22', '#': '%23', '$': '%24', '%': '%25', '&': '%26', '\'': '%27',
        '(': '%28', ')': '%29', '*': '%2A', '+': '%2B', ',': '%2C', '/': '%2F', ':': '%3A', ';': '%3B',
        '<': '%3C', '=': '%3D', '>': '%3E', '?': '%3F', '@': '%40', '[': '%5B', '\\': '%5C', ']': '%5D',
        '^': '%5E', '`': '%60', '{': '%7B', '|': '%7D', '~': '%7E'
    };

    return url.split('').map(char =>
        charMap[char] || char
    ).join('');
}

// 翻译方法
// function translate0(country) {
//     let content = encodeURL($("#user_input").val());
//     if (country === "美国" || country === "英国" || country === "加拿大") return content;
//     if (country === "西班牙" || country === "墨西哥") {

//     }
// }


let languages = ["com/s?k=", "co.uk/s?k=", "ca/s?k=",
    "fr/s?k=", "it/s?k=", "de/s?k=", "es/s?k=", "com.mx/s?k=",
    "nl/s?k=", "se/s?k=", "pl/s?k="];
let languages_zh = ["美国", "英国", "加拿大", "法国", "意大利", "德国", "西班牙", "墨西哥", "荷兰", "瑞典", "波兰"];
let languages_code = ["en", "en", "en", "fr", "it", "de", "es", "es", "nl", "se", "pl"];
let bt_container = document.getElementById("bt_container");
languages_zh.forEach(country => {
    // 创建按钮元素
    let btn = document.createElement("button");
    btn.textContent = country;
    btn.className = "bt";
    btn.style.margin = "5px";
    btn.style.padding = "8px 15px";

    // 添加点击事件
    btn.addEventListener("click", function () {
        let content = encodeURL($("#user_input").val());
        // let url = "https://www.amazon." + languages[languages_zh.indexOf(country)] + translate(country);
        let url = "https://www.amazon." + languages[languages_zh.indexOf(country)] + content;
        console.log(url)
        window.open(url, '_blank'); // 在新标签页中打开链接
        console.log(country); // 控制台输出
    });

    // 将按钮添加到容器
    bt_container.appendChild(btn);
});

function get_txt() {
    let product_name = "产品名称：" + $("#product_name").val();
    let country = "国家：" + $("#country").val();
    let price = "售价：" + $("#price").val() + "元";
    let cost_price = "拿货价：" + $("#cost_price").val() + "元";
    let delivery_time = "配送时间：" + $("#delivery_time").val();
    let package_size = "包装尺寸：" + $("#package_size_l").val() + "*" + $("#package_size_w").val() + "*" + $("#package_size_h").val() + "cm";
    let actual_weight = "实际重量：" + $("#actual_weight").val() + "kg";
    let throw_weight = "计抛重量：" + $("#throw_weight").val() + "kg";
    let is_electric_or_magnetic = "是否带电带磁：" + $("#is_electric_or_magnetic").val();
    let amazon_order_number = "亚马逊单号：" + $("#amazon_order_number").val();
    let order_remark = "下单备注：" + $("#order_remark").val();
    let purchase_link = "拿货链接：" + $("#purchase_link").val();
    return product_name + "\n" + country + "\n" + price + "\n" + cost_price + "\n" + delivery_time + "\n" + package_size + "\n" + actual_weight + "\n" + throw_weight + "\n" + is_electric_or_magnetic + "\n" + amazon_order_number + "\n" + order_remark + "\n" + purchase_link;
}

// 复制信息
$("#copy_info").click(function () {
    let text = get_txt();
    console.log(text)
    navigator.clipboard.writeText(text).then(function () {
        dhtmlx.message("复制成功!");
    }).catch(function (err) {
        console.message('复制失败: ', err);
    })
})

// 将信息保存到电脑
$("#save_info").click(function () {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    let text = get_txt();
    let blob = new Blob([text], {type: "text/plain;charset=utf-8"});
    let url = URL.createObjectURL(blob);
    console.log(url)
    let link = document.createElement("a");
    link.href = url;
    link.download = $("#sku").val() + "-" + $("#product_name").val() + `-${year}${month}${day}${hours}${minutes}${seconds}.txt`;
    link.click();
    URL.revokeObjectURL(url);
})


// 获取所有表单元素
const formInputs = document.querySelectorAll('input, textarea');
const storageKey = 'formData';

// 从本地存储加载数据
function loadFormData() {
    const savedData = localStorage.getItem(storageKey);
    if (savedData) {
        const formData = JSON.parse(savedData);
        formInputs.forEach(input => {
            if (formData[input.id]) {
                input.value = formData[input.id];
            }
        });
    }
}

// 保存数据到本地存储
function saveFormData() {
    const formData = {};
    formInputs.forEach(input => {
        formData[input.id] = input.value;
    });
    localStorage.setItem(storageKey, JSON.stringify(formData));
}

// 为所有输入框添加事件监听
formInputs.forEach(input => {
    input.addEventListener('input', saveFormData);
});

// 页面加载时恢复数据
window.addEventListener('DOMContentLoaded', loadFormData);


// 实时计算记抛
// 获取所有相关输入元素
const lengthInput = document.getElementById('package_size_l');
const widthInput = document.getElementById('package_size_w');
const heightInput = document.getElementById('package_size_h');
const throwWeightInput = document.getElementById('throw_weight');

// 为所有尺寸输入框添加输入事件监听
[lengthInput, widthInput, heightInput].forEach(input => {
    input.addEventListener('input', calculateVolumetricWeight);
});

function calculateVolumetricWeight() {
    // 获取长宽高值并转换为数字
    const length = parseFloat(lengthInput.value) || 0;
    const width = parseFloat(widthInput.value) || 0;
    const height = parseFloat(heightInput.value) || 0;

    // 计算体积重量（长*宽*高/6000）
    const volumetricWeight = (length * width * height) / 6000;

    // 将结果填入计抛重量输入框，保留2位小数
    throwWeightInput.value = volumetricWeight.toFixed(2);
    saveFormData()
}


// 粘贴全部按钮功能
document.getElementById("inst_info").addEventListener("click", function () {
    let modalHTML =
        `
                    <div id="PasteCustomModal" style="display: none; position: fixed; z-index: 1000; left: 50%; top: 50%; transform: translate(-50%, -50%); background: white; border: 1px solid #cccaaa; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.16);">
                      <textarea  id="PasteModalTextbox" placeholder="粘贴到此处..." style="width: 100%; margin-bottom: 10px; padding: 8px; box-sizing: border-box;" />
                      </br>
                      <button id="PasteVerifyBtn" style="margin-right: 0px; padding: 8px 16px;">确定</button>
                      <button id="PasteClearBtn"   style="margin-right: 0px; padding: 8px 16px;">清空</button>
                      <button id="PasteCloseBtn"   style="margin-right: 0px; padding: 8px 16px;">关闭</button>
                  </div>
                `;
    // 将模态对话框添加到页面中
    $("body").append(modalHTML);
    // 获取模态对话框和相关元素的引用
    var PasteCustomModal = $("#PasteCustomModal");
    var PasteModalTextbox = $("#PasteModalTextbox");
    var PasteVerifyBtn = $("#PasteVerifyBtn");
    var PasteClearBtn = $("#PasteClearBtn");
    var PasteCloseBtn = $("#PasteCloseBtn");
    // 显示模态对话框
    PasteCustomModal.show();
    PasteModalTextbox.val("");
    PasteModalTextbox.focus();
    // 为确认按钮添加点击事件
    PasteVerifyBtn.on("click", function () {
        var text = PasteModalTextbox.val();
        const lines = text.split(/\r?\n/);
        console.log(lines);
        let result = lines;
        // console.log(result);
        if (result.length === 12) {
            // 产品名称
            document.getElementById('product_name').value = result[0].split('：')[1];

            // 国家
            document.getElementById('country').value = result[1].split('：')[1];

            // SKU（未提供，此处留空）
            document.getElementById('sku').value = '';

            // 售价
            document.getElementById('price').value = parseFloat(result[2].split('：')[1].replace('元', ''));

            // 拿货价
            document.getElementById('cost_price').value = parseFloat(result[3].split('：')[1].replace('元', ''));

            // 配送时间
            document.getElementById('delivery_time').value = result[4].split('：')[1];

            // 包装尺寸（长、宽、高）
            var packageSizeParts = result[5].split('：')[1].split('*'); // 先分割出"30*24*8cm"，再分割成长宽高部分

            // 将值赋给对应的文本框
            document.getElementById('package_size_l').value = parseFloat(packageSizeParts[0]);
            document.getElementById('package_size_w').value = parseFloat(packageSizeParts[1]);
            document.getElementById('package_size_h').value = parseFloat(packageSizeParts[2].split('cm')[0]);


            // 计抛重量
            document.getElementById('throw_weight').value = parseFloat(result[6].split('：')[1].replace('kg', ''));

            // 实际重量
            document.getElementById('actual_weight').value = parseFloat(result[7].split('：')[1].replace('kg', ''));

            // 是否带电带磁
            document.getElementById('is_electric_or_magnetic').value = result[8].split('：')[1];

            // 亚马逊单号
            document.getElementById('amazon_order_number').value = result[9].split('：')[1];

            // 下单备注
            document.getElementById('order_remark').value = result[10].split('：')[1];

            // 拿货链接
            document.getElementById('purchase_link').value = result[11].split('：')[1];

            PasteCustomModal.hide();

            dhtmlx.message("写入完成");
        } else {
            dhtmlx.message("长度异常");
        }
    });

    // 为清空按钮添加点击事件
    PasteClearBtn.on("click", function () {
        PasteModalTextbox.val(""); // 清空文本框内容
    });
    // 为关闭按钮添加点击事件
    PasteCloseBtn.on("click", function () {
        PasteCustomModal.hide();
    });
    // 阻止模态对话框内部的点击事件冒泡到文档（可选，但推荐）
    PasteCustomModal.on("click", function (e) {
        e.stopPropagation();
    });

})
// function PasteAll() {
//     var zhan_tie = $(
//         '<a id="pasteall" class="layui-btn fanyis" style="background-color: #bfa25b; ">粘贴全部</a>'
//     ).click(function () {
//         // 创建模态对话框的HTML结构
//         var modalHTML =
//             `
//                     <div id="PasteCustomModal" style="display: none; position: fixed; z-index: 1000; left: 50%; top: 50%; transform: translate(-50%, -50%); background: white; border: 1px solid #ccc; padding: 20px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);">
//                       <textarea  id="PasteModalTextbox" placeholder="粘贴到此处..." style="width: 100%; margin-bottom: 10px; padding: 8px; box-sizing: border-box;" />
//                       </br>
//                       <button id="PasteVerifyBtn" style="margin-right: 0px; padding: 8px 16px;">确定</button>
//                       <button id="PasteClearBtn"   style="margin-right: 0px; padding: 8px 16px;">清空</button>
//                       <button id="PasteCloseBtn"   style="margin-right: 0px; padding: 8px 16px;">关闭</button>
//                   </div>
//                 `;
//
//         // 将模态对话框添加到页面中
//         $("body").append(modalHTML);
//         // 获取模态对话框和相关元素的引用
//         var PasteCustomModal = $("#" + language + "PasteCustomModal");
//         var PasteModalTextbox = $("#" + language + "PasteModalTextbox");
//         var PasteVerifyBtn = $("#" + language + "PasteVerifyBtn");
//         var PasteClearBtn = $("#" + language + "PasteClearBtn");
//         var PasteCloseBtn = $("#" + language + "PasteCloseBtn");
//         // 显示模态对话框
//         PasteCustomModal.show();
//         PasteModalTextbox.val("");
//         PasteModalTextbox.focus();
//         // 为确认按钮添加点击事件
//         PasteVerifyBtn.on("click", function () {
//             var text = PasteModalTextbox.val();
//             const lines = text.split(/\r?\n/);
//             // console.log(lines);
//             let result = [];
//             for (let i = 0; i < lines.length; i++) {
//                 if (lines[i] != "") result.push(lines[i]);
//                 else if (lines[i - 1] != "" && i > 9) result.push("*******");
//             }
//             // console.log(result);
//             if (result.length > 6) {
//                 $("#" + language + "title").val(result[0]);
//                 $("#" + language + "content").val(result.slice(1, 6).join("\n"));
//                 $("#" + language + "descript").val(result.slice(7).join("\n"));
//                 // console.log(result.length);
//                 // console.log(text);
//                 // console.log("--------------------------");
//                 // for (let i = 0; i < result.length; i++) {
//                 //     console.log(i+":"+result[i]);
//                 // }
//                 PasteCustomModal.hide(); // 隐藏模态对话框
//                 msgTip("【" + getLanguageName(language) + "】粘贴成功", 1, 1500);
//                 dhtmlx.message("【" + getLanguageName(language) + "】粘贴成功!");
//                 $("#randomLineWrapping").click();
//                 dhtmlx.message("【随机换行】执行完成");
//                 $("#subheadingsCapitalized").click();
//                 dhtmlx.message("【小标题大写】执行完成");
//             } else {
//                 msgTip("行数错误，标题1行，五点5行，描述最少1行！", 2, 1500);
//             }
//         });
//
//         // 为清空按钮添加点击事件
//         PasteClearBtn.on("click", function () {
//             PasteModalTextbox.val(""); // 清空文本框内容
//         });
//         // 为关闭按钮添加点击事件
//         PasteCloseBtn.on("click", function () {
//             PasteCustomModal.hide();
//         });
//         // 阻止模态对话框内部的点击事件冒泡到文档（可选，但推荐）
//         PasteCustomModal.on("click", function (e) {
//             e.stopPropagation();
//         });
//     });
//     $(selector).append(zhan_tie);
// }
//
// PasteAll()